package message

import (
	"gitee.com/cooge/impush/gutil"
	"gitee.com/cooge/impush/util"
)

var md *gutil.LinkMap

func init() {
	md = gutil.NewLinkMap()
}
func LoginSuccess() []byte {
	m := md.Get(LOGIN_SUCCESS)
	if m != nil {
		return m.([]byte)
	}
	var msg_ Message
	head := make(Head)
	head[TYPE] = LOGIN
	head[STATUS] = SUCCESS
	msg_.Heads = head
	data := msg_.MessageToByte()
	md.Add(LOGIN_SUCCESS, data)
	return data
}

func Live() []byte {
	m := md.Get(LIVE)
	if m != nil {
		return m.([]byte)
	}
	var msg Message
	head := make(Head)
	head[TYPE] = LIVE
	msg.Heads = head
	data := msg.MessageToByte()
	md.Add(LIVE, data)
	return data
}

func ClusterLive() []byte {
	var msg Message
	head := make(Head)
	msg.Heads = head
	head[TYPE] = CLUSTER
	head[ACTION] = LIVE
	data := msg.MessageToByte()
	return data

}

/*根据用户ID 向用户发送信息*/
func GetSystemMessage(userid string, mesg string) *Message {
	return GetMessage(userid, SYSTEM, mesg)
}
func GetMessage(touserid string, fromuserId, mesg string) *Message {
	var msg Message
	head := make(Head)
	msg.Heads = head
	head[TYPE] = MESSAGE
	head[TO] = touserid
	head[FROM] = fromuserId
	msg.Body = []byte(mesg)
	return &msg
}

func SendSuccess(msgid string) *Message {
	var msg Message
	head := make(Head)
	msg.Heads = head
	head[TYPE] = TRACK
	head[MESSAGE_ID] = msgid
	head[RESULT] = SUCCESS
	return &msg
}
func SendFail(msgid string) *Message {
	var msg Message
	head := make(Head)
	msg.Heads = head
	head[TYPE] = TRACK
	head[MESSAGE_ID] = msgid
	head[RESULT] = FAIL
	return &msg
}

func StartLogin() []byte {
	m := md.Get(LOGIN)
	if m != nil {
		return m.([]byte)
	}
	var msg Message
	head := make(Head)
	msg.Heads = head
	head[TYPE] = LOGIN
	head[STATUS] = START

	data := msg.MessageToByte()
	md.Add(LOGIN, data)
	return data

}

func SendMachinesNoUser(userid ...string) []byte {
	var msg Message
	head := make(Head)
	head[TYPE] = CLUSTER
	head[ACTION] = NO_USER
	msg.Heads = head
	msg.Body = util.Join(userid, ";")
	return msg.MessageToByte()
}

func SendClusterLiveMessage(address []string) []byte {
	var msg Message
	head := make(Head)
	head[TYPE] = CLUSTER
	head[ACTION] = LIVE
	msg.Heads = head
	msg.Body = util.Join(address, ";")
	return msg.MessageToByte()
}
